from fastapi import APIRouter
from fastapi.responses import JSONResponse
import structlog
import redis
import httpx

from config.settings import settings
from app.services.service_instances import service_discovery

logger = structlog.get_logger()
router = APIRouter(tags=["Health"])


@router.get("/")
async def health_check():
    """网关服务健康检查"""
    health_status = {
        "status": "healthy",
        "services": "suna-gateway",
        "version": settings.app_version,
        "timestamp": None
    }

    # 检查Redis连接
    redis_status = "healthy"
    try:
        redis_client = redis.from_url(settings.redis_url)
        redis_client.ping()
    except Exception as e:
        redis_status = f"unhealthy: {str(e)}"
        health_status["status"] = "unhealthy"

    # 获取服务状态
    services_status = service_discovery.get_service_status()

    # 检查是否有不健康的服务
    unhealthy_services = [
        name for name, status in services_status.items()
        if not status["is_healthy"]
    ]

    if unhealthy_services:
        health_status["status"] = "degraded"

    health_status.update({
        "redis": redis_status,
        "services": services_status,
        "unhealthy_services": unhealthy_services,
        "timestamp": None  # 将由中间件添加
    })

    status_code = 200 if health_status["status"] == "healthy" else 503

    return JSONResponse(
        content=health_status,
        status_code=status_code
    )


@router.get("/ready")
async def readiness_check():
    """就绪检查"""
    checks = {
        "redis": False,
        "services_loaded": False
    }

    # 检查Redis
    try:
        redis_client = redis.from_url(settings.redis_url)
        redis_client.ping()
        checks["redis"] = True
    except Exception:
        pass

    # 检查服务是否已加载
    if service_discovery.services:
        checks["services_loaded"] = True

    all_ready = all(checks.values())

    return JSONResponse(
        content={
            "ready": all_ready,
            "checks": checks
        },
        status_code=200 if all_ready else 503
    )


@router.get("/live")
async def liveness_check():
    """存活检查"""
    return {"status": "alive", "services": "suna-gateway"}